<?php
class PartsController extends AppController {

	var $name = 'Parts';
	var $uses = array('Part','Batch');
    
    
	function admin_index($id) {
		
		$batch = $this->Batch->findById($id);
		$this->Part->checkAndCreate($batch,$this->settings['multiple_chioce_questions'],$this->settings['essay_questions']);
		$this->paginate['Part'] = array('conditions'=>array('Part.batch_id'=>$id));
		$this->Part->recursive = 0;
		$this->set('batch', $batch);
		$this->set('parts', $this->paginate('Part'));
	}

	function admin_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid part', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('part', $this->Part->read(null, $id));
	}

	function admin_add($id=null) {
	
	if($id==null) $this->redirect('/admin/batches/index');
		$batch = $this->Batch->findById($id);	
		if (!empty($this->data)) {
			$this->Part->create();
			if ($this->Part->save($this->data)) {
				$this->Session->setFlash(__('The part has been saved', true));
				$this->redirect(array('action' => 'index',$batch['Batch']['id']));
			} else {
				$this->Session->setFlash(__('The part could not be saved. Please, try again.', true));
			}
		}
		$batches = $this->Part->Batch->find('list');
		$this->set(compact('batches'));
		
		$this->set('batch',$batch);
	}

	function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid part', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Part->save($this->data)) {
				$this->Session->setFlash(__('The part has been saved', true));
				$this->data = $this->Part->read(null, $id);
				$this->redirect('/admin/parts/index/'.$this->data['Part']['batch_id']);
			} else {
				$this->Session->setFlash(__('The part could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Part->read(null, $id);
		}
		$batches = $this->Part->Batch->find('list');
		$this->set(compact('batches'));
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for part', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Part->delete($id)) {
			$this->Session->setFlash(__('Part deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Part was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
}
